var http = require('http');
var querystring = require('querystring');
var util = require('util');

var g_FriendList;

server();

function server()
{
	readFriendInfoFromDb();

	http.createServer(function(req, res) {
		res.setHeader('Access-Control-Allow-Origin', '*');
		res.writeHead(200, {
			'Content-Type': 'text/html'
		});

		var recvData = '';

		req.on('data', function(chunk) {
			recvData += chunk;
		});

		req.on('end', function() {
			var jsonFormatRecvData = JSON.parse(recvData);
			var resJson = parsePacket(jsonFormatRecvData);
			res.end(resJson);
			console.log("cmd:" + jsonFormatRecvData.cmd);
		});
	}).listen(8081);

	console.log('Server running at 127.0.0.1');
}

function Fri_Info(name,imgSrc,account)
{
	this.name = name;
	this.imgSrc = imgSrc;
	this.account = account;
	this.IPAddr ="";
	this.pwd = (parseInt(account)+1);

	this.getIPAddr = function () {
		return this.IPAddr;
	};
	
	this.setIPAddr = function (IPAddr) {
		 this.IPAddr = IPAddr;
	};

	this.getPwd = function(){
		return this.pwd;
	};

	this.setPwd = function(newPwd)
	{
		this.pwd = newPwd;
	}
}

function readFriendInfoFromDb() {
	g_FriendList = new Array();
	g_FriendList[0] = new Fri_Info("吴晓霞","friend_pic_1.jpg","10001");
	g_FriendList[1] = new Fri_Info("伍思河","friend_pic_2.jpg","10002"); 
	g_FriendList[2] = new Fri_Info("刘慧娴","friend_pic_3.jpg","10003");
	g_FriendList[3] = new Fri_Info("刘春宜","friend_pic_6.jpg","10004"); 
	g_FriendList[4] = new Fri_Info("刘杰铖","friend_pic_5.jpg","10005"); 
}

function retFriendInfoByAccount(account){
	var i = 0;
	var curr_FriendInfo ='';

	for ( i = 0 ; i < g_FriendList.length ; i++)
	{
		if ( g_FriendList[i].account == account)
		{
			curr_FriendInfo = g_FriendList[i];
			break;
		}
	}

	return curr_FriendInfo;
}

function prepareLoginRes(Fri_Info)
{
	if (Fri_Info != '')
	{
		return JSON.stringify(
		{
			cmd:"Server_Login_Res_Cmd",
			len:"4",
			status:"1",
			account:Fri_Info.account, 
			password:Fri_Info.pwd,
			name:Fri_Info.name
		});
	}
	else
	{
		return JSON.stringify(
		{
			cmd:"Server_Login_Res_Cmd",
			len:"1",
			status:"0",
		});
	}
}

function parsePacket(jsonPacket){
	var ret = '';
	console.log("account:"+jsonPacket.account);
	switch(jsonPacket.cmd){
		case "Client_Login_Req_Cmd":
		ret = prepareLoginRes(retFriendInfoByAccount(jsonPacket.account));
		break;
	}

	return ret;
}

